//
//  MGReceiptController.m
//  MoneyRecord_iOS
//
//  Created by alchemy on 2022/2/27.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGReceiptController.h"
#import "MGAccountController.h"
#import "MGAccountsController.h"
#import "MGCategoryController.h"
#import "MGCategoriesController.h"

#import "MGReceiptMoneyCell.h"
#import "MGReceiptRemarkCell.h"
#import "MGBaseBorderDetailCell.h"

#import "MGReceiptKeyBoardView.h"
#import "MGReceiptSwitchView.h"
#import "MGGestureScrollView.h"
#import <YYBBaseViews/YYBMultiScrollContainerView.h>

#import "NSString+ReceiptAdd.h"

@interface MGReceiptController () <YYBMultiScrollContainerViewDelegate>
@property (nonatomic, strong) MGReceiptKeyBoardView *keyboardView;
@property (nonatomic, strong) MGReceiptSwitchView *receiptSwitchView;
@property (nonatomic, strong) YYBMultiScrollContainerView *scrollContainerView;

@property (nonatomic, copy) NSString *calculateString;
@property (nonatomic) BOOL shouldOpenCategory, shouldOpenAccount;

@end

@implementation MGReceiptController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.enableNavigationShadows = NO;
    
    if (self.updateModel) {
        self.dataModel = [MGReceiptModel yy_modelWithJSON:self.updateModel.yy_modelToJSONObject];
        
        self.dataModel.savedMoney = self.updateModel.savedMoney ? : self.updateModel.shouldSaveMoney;
        self.calculateString = [self.dataModel getReceiptMoneyString];
    } else {
        // 新建一个账单
        self.dataModel = [[MGReceiptModel alloc] init];
        if (self.selectedDate) {
            self.dataModel.actualSaveTime = self.selectedDate.timeIntervalSince1970;
        }
        
        if (MGConfigManager.shared.dataModel.enableTimeMemory) {
            NSTimeInterval memoryTs = MGConfigManager.shared.dataModel.timeMemoryTs;
            if (memoryTs != 0) {
                self.dataModel.actualSaveTime = memoryTs;
            }
        }
    }
    
    self.dataModel.recordUniqueId = self.recordModel.uniqueId;
    if (self.dataModel.categoryUniqueId == 0) {
        self.dataModel.categoryUniqueId = [MGCategoryAccessor.shared getStandardCategoryModel].uniqueId;
    }
    if (self.dataModel.accountUniqueId == 0) {
        self.dataModel.accountUniqueId = [MGAccountAccessor.shared getStandardAccountModel].uniqueId;
    }
    if (self.dataModel.actualSaveTime == 0) {
        self.dataModel.actualSaveTime = [NSDate date].timeIntervalSince1970;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.shouldOpenCategory) {
        [self handleSelectCategory];
        self.shouldOpenCategory = NO;
    }
    
    if (self.shouldOpenAccount) {
        [self handleSelectAccount];
        self.shouldOpenAccount = NO;
    }
}

- (void)beginConfigViewAction {
    [super beginConfigViewAction];
    
    MGGestureScrollView *scrollView = [[MGGestureScrollView alloc] init];
    self.scrollContainerView = [[YYBMultiScrollContainerView alloc] initWithScrollView:scrollView];
    self.scrollContainerView.delegate = self;
    self.scrollContainerView.scrollView.bounces = NO;
    self.scrollContainerView.scrollView.directionalLockEnabled = YES;
    [self.view addSubview:self.scrollContainerView];
    [self.scrollContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 计算器
    self.keyboardView = [[MGReceiptKeyBoardView alloc] init];
    [self.view addSubview:self.keyboardView];
    [self.keyboardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(225 + 45 + 2 + 20 + [UIDevice safeAreaInsetsBottom]);
    }];

    @weakify(self);
    self.keyboardView.stringChangedBlock = ^(NSString *text) {
        @strongify(self);
        [self handleCalculateWithString:text];
    };
    self.keyboardView.dismissTapedBlock = ^{
        @strongify(self);
        [self handleKeyboardTransform];
    };
    self.keyboardView.completeTapedBlock = ^{
        @strongify(self);
        [self _handleComplete];
    };
    self.keyboardView.actionTapedBlock = ^(NSInteger index) {
        @strongify(self);
        if (index == 0) {
            [self handleDeleteReceipt];
        }
    };
    
    if (!self.updateModel) {
        // 隐藏键盘的删除按钮
        self.keyboardView.hidesDeleteAction = YES;
    }
}

- (void)configCustomNavigationBar:(YYBNavigationBar *)navigationBar {
    [super configCustomNavigationBar:navigationBar];
    
    @weakify(self);
    YYBNavigationBarButton *completeButton = [YYBNavigationBarButton buttonWithConfigureBlock:^(YYBNavigationBarButton *container, UIButton *view) {
        container.contentSize = CGSizeMake(55, 28);
        container.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
        
        [view cornerRadius:14];
        [view setTitle:@"保存" forState:0];
        [view setTitleColor:APP_COLOR_MAIN forState:0];
        view.backgroundColor = [APP_COLOR_MAIN colorWithAlphaComponent:0.1];
        view.titleLabel.font = FONT_REGULAR(14);
    } tapedActionBlock:^(YYBNavigationBarContainer *view) {
        @strongify(self);
        [self _handleComplete];
    }];
    
    navigationBar.rightBarContainers = @[completeButton];
}

- (void)beginQueryData {
    [super beginQueryData];
    
    [self.scrollContainerView refreshScrollContainerView];
    [self.receiptSwitchView handleChangeReceiptType];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.scrollContainerView containerViewScrollToItemIndex:self.dataModel.receiptType];
}

- (UIView *)customNavigationBarTitleView {
    // 顶部的支出、收入的选项
    self.receiptSwitchView = [[MGReceiptSwitchView alloc] init];
    self.receiptSwitchView.frame = CGRectMake(0, 0, 120, 44);
    
    @weakify(self);
    self.receiptSwitchView.getSelectTypeBlock = ^MGReceiptType{
        @strongify(self);
        return self.dataModel.receiptType;
    };
    self.receiptSwitchView.receiptTypeSelectBlock = ^(MGReceiptType type) {
        @strongify(self);
        self.dataModel.receiptType = type;
        [self.scrollContainerView containerViewScrollToItemIndex:type];
    };
    
    return self.receiptSwitchView;
}

- (void)_handleComplete {
    if (self.updateModel) {
        [self handleUpdateReceiptAction];
    } else {
        [self handleCreateReceiptAction];
    }
}

- (BOOL)dataModelValid {
    if (self.dataModel.savedMoney.floatValue == 0) {
        [YYBAlertView showAlertViewWithStatusString:@"请输入金额"];
        return NO;
    } else if (self.dataModel.remark.length > 20) {
        [YYBAlertView showAlertViewWithStatusString:@"备注长度不能大于20个字符"];
        return NO;
    }
    return YES;
}

// 删除记录
- (void)handleDeleteReceipt {
    @weakify(self);
    [MGAlertView showAlertViewWithTitle:nil detail:@"确定删除这条账单吗?" firstActionTitle:@"取消" firstActionTapedBlock:^{
        
    } secondActionTitle:@"确定" secondActionTapedBlock:^{
        @strongify(self);
        [self _handleDeleteReceipt];
    }];
}

- (void)_handleDeleteReceipt {
    @weakify(self);
    if (MGOssManager.shouldUpload) {
        self.refreshAlertView = [MGAlertView showLoadingWithString:@"删除中" inView:self.view];
    }
    [MGRecordAccessor.shared deleteReceiptModel:self.updateModel recordModel:self.recordModel completeBlock:^{
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showString:@"删除成功"];
        self.deleteSuccBlock();
        [self.navigationController popViewControllerAnimated:YES];
    } errorBlock:^(NSError *error) {
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showError:error];
    }];
}

// ===============================================================================
// 添加、修改收支记录
- (void)handleCreateReceiptAction {
    if ([self dataModelValid]) {
        @weakify(self);
        if (MGOssManager.shouldUpload) {
            self.refreshAlertView = [MGAlertView showLoadingWithString:@"添加中" inView:self.view];
        }
        [MGRecordAccessor.shared createReceiptModel:self.dataModel recordModel:self.recordModel completeBlock:^{
            @strongify(self);
            [MGConfigManager.shared configWithBlock:^(MGConfigModel * _Nonnull dataModel) {
                dataModel.timeMemoryTs = self.dataModel.actualSaveTime;
            }];
            [MGAlertView closeAlertView:self.refreshAlertView showString:@"添加成功"];
            if (self.updateSuccBlock) {
                self.updateSuccBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        } errorBlock:^(NSError *error) {
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showError:error];
        }];
    }
}

- (void)handleUpdateReceiptAction {
    if ([self dataModelValid]) {
        @weakify(self);
        if (MGOssManager.shouldUpload) {
            self.refreshAlertView = [MGAlertView showLoadingWithString:@"修改中" inView:self.view];
        }
        [MGRecordAccessor.shared updateReceiptModel:self.updateModel shouldUpdateModel:self.dataModel recordModel:self.recordModel completeBlock:^{
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showString:@"修改成功"];
            if (self.updateSuccBlock) {
                self.updateSuccBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        } errorBlock:^(NSError *error) {
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showError:error];
        }];
    }
}

// 选择账户
- (void)handleSelectAccount {
    @weakify(self);
    MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.dataModel.accountUniqueId];
    if (!accountModel) {
        accountModel = [MGAccountAccessor.shared getStandardAccountModel];
    }
    
    [MGAlertView showAccountsAlertViewWithSelectModel:accountModel selectedBlock:^(MGAccountModel * _Nonnull dataModel) {
        @strongify(self);
        self.dataModel.accountUniqueId = dataModel.uniqueId;
        [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenAccount = YES;
            [self createAccount];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenAccount = YES;
            [self getIntoAccountList];
        }
    }];
}

// 选择类型
- (void)handleSelectCategory {
    @weakify(self);
    // 获取当前的选中的类别
    MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.dataModel.categoryUniqueId];
    if (!categoryModel) {
        categoryModel = [MGCategoryAccessor.shared getStandardCategoryModel];
    }
    
    [MGAlertView showCategoriesAlertViewWithSelectModel:categoryModel selectedBlock:^(MGCategoryModel * _Nonnull dataModel) {
        @strongify(self);
        self.dataModel.categoryUniqueId = dataModel.uniqueId;
        [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenCategory = YES;
            [self createCategory];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenCategory = YES;
            [self getIntoCategoryList];
        }
    }];
}

// 选择日期
- (void)handleSelectDate {
    @weakify(self);
    NSDate *selectDate = [NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime];
    [MGAlertView showReceiptDateAlertViewWithDate:selectDate dateOrTime:self.dataModel.dateOrTime dateSelectBlock:^(NSDate * _Nonnull date, BOOL dateOrTime) {
        @strongify(self);
        self.dataModel.dateOrTime = dateOrTime;
        self.dataModel.actualSaveTime = date.timeIntervalSince1970;
        [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
    }];
}

- (void)createAccount {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGAccountController class] configureBlock:^(MGAccountController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.accountUniqueId) {
                self.dataModel.accountUniqueId = 0;
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
        obj.createModelBlock = ^(NSUInteger uniqueId) {
            self.dataModel.accountUniqueId = uniqueId;
            [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.accountUniqueId) {
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
    }];
}

- (void)getIntoAccountList {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGAccountsController class] configureBlock:^(MGAccountsController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.accountUniqueId) {
                self.dataModel.accountUniqueId = 0;
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
        obj.createModelBlock = ^(NSUInteger uniqueId) {
            self.dataModel.accountUniqueId = uniqueId;
            [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.accountUniqueId) {
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
    }];
}

- (void)createCategory {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGCategoryController class] configureBlock:^(MGCategoryController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.categoryUniqueId) {
                self.dataModel.categoryUniqueId = 0;
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
        obj.createModelBlock = ^(NSUInteger uniqueId) {
            self.dataModel.categoryUniqueId = uniqueId;
            [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.categoryUniqueId) {
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
    }];
}

- (void)getIntoCategoryList {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGCategoriesController class] configureBlock:^(MGCategoriesController *obj) {
        @strongify(self);
        obj.deleteModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.categoryUniqueId) {
                self.dataModel.categoryUniqueId = 0;
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
        obj.createModelBlock = ^(NSUInteger uniqueId) {
            self.dataModel.categoryUniqueId = uniqueId;
            [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
        };
        obj.updateModelBlock = ^(NSUInteger uniqueId) {
            if (uniqueId == self.dataModel.categoryUniqueId) {
                [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
            }
        };
    }];
}

// YYBMultiScrollContainerViewDelegate
- (NSInteger)numbersOfSectionInContainerView:(YYBMultiScrollContainerView *)containerView {
    return 2;
}

- (void)configureTableViewInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex {
    tableView.backgroundColor = APP_COLOR_BACKGROUND;
    tableView.contentInset = UIEdgeInsetsMake([self customPageHeaderHeight] + 10, 0, 0, 0);
    [tableView registerClass:[MGReceiptMoneyCell class] forCellReuseIdentifier:@"MGReceiptMoneyCell"];
    [tableView registerClass:[MGReceiptRemarkCell class] forCellReuseIdentifier:@"MGReceiptRemarkCell"];
    [tableView registerClass:[MGBaseBorderDetailCell class] forCellReuseIdentifier:@"MGBaseBorderDetailCell"];
}

- (NSInteger)numbersOfSectionsInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex {
    return 1;
}

- (NSInteger)numbersOfRowsInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex section:(NSInteger)section {
    return 5;
}

- (CGFloat)heightForRowsInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex indexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100;
    } else if (indexPath.row == 4) {
        return 90;
    }
    return 50;
}

- (UITableViewCell *)cellForRowInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex indexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MGReceiptMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGReceiptMoneyCell"];

        BOOL isPunched = self.dataModel.actualSaveTime != 0;
        [cell configViewWithTitleValue:self.calculateString receiptType:self.dataModel.receiptType isPunched:isPunched];
        return cell;
    } else if (indexPath.row == 1) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *account = @"请选择账户";
        if (self.dataModel.accountUniqueId != 0) {
            MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.dataModel.accountUniqueId];
            account = accountModel.name;
        }
        
        [cell configViewWithCornerType:MGCornerTypeTop];
        [cell configViewWithTitleValue:@"账户" detailValue:account iconName:@"ico_common_card"];
        return cell;
    } else if (indexPath.row == 2) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *categoryName = @"请选择分类";
        if (self.dataModel.categoryUniqueId != 0) {
            MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.dataModel.categoryUniqueId];
            categoryName = categoryModel.name;
        }
        
        [cell configViewWithCornerType:MGCornerTypeCenter];
        [cell configViewWithTitleValue:@"分类" detailValue:categoryName iconName:@"ico_common_cate"];
        return cell;
    } else if (indexPath.row == 3) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *date = nil;
        if (self.dataModel.dateOrTime) {
            date = [[NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime] toStringWithFormatter:@"M月d日"];
        } else {
            date = [[NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime] toStringWithFormatter:@"M月d日 HH:mm"];
        }
        
        [cell configViewWithCornerType:MGCornerTypeBottom];
        [cell configViewWithTitleValue:@"日期" detailValue:date iconName:@"ico_common_date"];
        return cell;
    } else if (indexPath.row == 4) {
        // 备注
        MGReceiptRemarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGReceiptRemarkCell"];
        
        @weakify(self);
        cell.stringChangedBlock = ^(NSString *text) {
            @strongify(self);
            self.dataModel.remark = text;
        };
        
        [cell configViewWithCornerType:MGCornerTypeAll];
        [cell configViewWithTitleValue:self.dataModel.remark];
        return cell;
    }
    return nil;
}

- (void)didSelectedRowInContainerView:(YYBMultiScrollContainerView *)containerView tableView:(UITableView *)tableView itemIndex:(NSInteger)itemIndex indexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (!CGAffineTransformEqualToTransform(CGAffineTransformIdentity, self.keyboardView.transform)) {
            [self handleKeyboardTransform];
        }
    } else if (indexPath.row == 1) {
        [self handleSelectAccount];
    } else if (indexPath.row == 2) {
        [self handleSelectCategory];
    } else if (indexPath.row == 3) {
        [self handleSelectDate];
    }
}

- (void)containerView:(YYBMultiScrollContainerView *)containerView didEndScrollAnimationAtItemIndex:(NSInteger)itemIndex {
    self.dataModel.receiptType = itemIndex;
    [self.receiptSwitchView handleChangeReceiptType];
    [self.scrollContainerView refreshContainerViewAtIndex:[self.scrollContainerView itemIndex]];
}

- (void)handleKeyboardTransform {
    [UIView animateWithDuration:0.2f animations:^{
        if (CGAffineTransformEqualToTransform(CGAffineTransformIdentity, self.keyboardView.transform)) {
            self.keyboardView.transform = CGAffineTransformMakeTranslation(0, CGRectGetHeight(self.keyboardView.frame));
        } else {
            self.keyboardView.transform = CGAffineTransformIdentity;
        }
    }];
}

- (void)handleCalculateWithString:(NSString *)string {
    self.calculateString = [NSString _handleCalculateWithSting:string calculateString:self.calculateString];

    NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithFloat:[self.calculateString calculateData]];
    self.dataModel.savedMoney = number;
    
    // 刷新当前的tableView
    NSInteger itemIndex = [self.scrollContainerView itemIndex];
    [self.scrollContainerView refreshContainerViewAtIndex:itemIndex];
}

@end
